import 'package:ai_data_capture/bean/TemplateBean.dart';
import 'package:ai_data_capture/main.dart';
import 'package:ai_data_capture/page/tasklist/add_template/logic.dart';
import 'package:ai_data_capture/req/api/ConfigApi.dart';
import 'package:ai_data_capture/req/api/FlowApi.dart';
import 'package:ai_data_capture/req/api/TaskApi.dart';
import 'package:ai_data_capture/req/exp.dart';
import 'package:ai_data_capture/util/toast_util.dart';
import 'package:get/get.dart';

import 'state.dart';

class TaskListLogic extends GetxController {
  final TasklistState state = TasklistState();
  bool is_continue_to_get = true;
  @override
  void onInit() {
    super.onInit();
    startGetLoop();
  }

  Future<void> refreshList() async {
    var tlist = await TaskApi.getTaskList();
    state.taskList.clear();
    state.taskList.addAll(tlist);
    var tmplist = await TaskApi.getTemplates();
    state.templates.clear();
    state.templates.addAll(tmplist);
  }

  void startGetLoop() async {
    while (true) {
      if (!is_continue_to_get) {
        break;
      }
      await continue_get();
      await Future.delayed(const Duration(seconds: 3));
    }
  }

  Future continue_get() async {
    try {
      refreshList();
    } catch (e) {
      if (e is ApiException) {
        print(e.message);
      }
      print(e);
    }
  }

  Future<void> deleteTemplate(String id) async {
    try {
      await TaskApi.deleteTemplate(id);
    } catch (e) {
      if (e is ApiException) {
        showToast(e.message);
      } else {
        showToast("$e");
      }
    }
    refreshList();
  }

  Future<void> changeTemplate(TemplateBean bean) async {
    try {
      var config = await ConfigApi.getConfigById(bean.configId);
      var flow = await FlowApi.getFlowById(bean.flowId);
      Get.toNamed(RoutePath.addTemplate,
          arguments: AddTempBean(
              id: bean.id,
              isAdd: false,
              configFileBean: config,
              flowBean: flow,
              desc: bean.description));
    } catch (e) {
      print(e);
    }
  }

  Future<void> addToChannel(TemplateBean bean) async {
    try {
      await TaskApi.addTempToChannel(bean);
    } catch (e) {
      if (e is ApiException) {
        showToast(e.message);
      } else {
        showToast("$e");
      }
    }
  }

  @override
  void onClose() {
    super.onClose();
    is_continue_to_get = false;
  }

  Future<void> removetask() async {
    try {
      await TaskApi.removeFinishedTask();
    } catch (e) {
      if (e is ApiException) {
        showToast(e.message);
      } else {
        showToast("$e");
      }
    }
    refreshList();
  }
}
